import pymysql

class SimpleMySQLHelper(object):
    def __init__(self):
        pass

    def open_conn(self):
        return pymysql.connect(
            host='127.0.0.1',
            user='zhihuspider',
            password='zhihuspider',
            db='zhihuspider',
            charset='utf8',
            cursorclass=pymysql.cursors.DictCursor
        )

    def select_one(self, sql, value_tuple):
        conn = self.open_conn()
        try:
            with conn.cursor() as cursor:
                cursor.execute(sql, value_tuple)
            result = cursor.fetchone()
            return result
        finally:
            conn.close()

    def select_all(self, sql, value_tuple):
        conn = self.open_conn()
        try:
            with conn.cursor() as cursor:
                cursor.execute(sql, value_tuple)
            result = cursor.fetchall()
            return result
        finally:
            conn.close()

    def execute(self, sql, value_tuple):
        conn = self.open_conn()
        try:
            with conn.cursor() as cursor:
                affected_row_count = cursor.execute(sql, value_tuple)
            return affected_row_count
        finally:
            conn.close()

    def execute_many(self, sql, value_tuple):
        conn = self.open_conn()
        try:
            with conn.cursor() as cursor:
                affected_row_count = cursor.executemany(sql, value_tuple)
            return affected_row_count
        finally:
            conn.close()